﻿using System.Collections.ObjectModel;
using System.Linq;
using LiftHub.Data;
using LiftHub.Data.TodoModels;

namespace LiftHub.ViewModels.Pages;

public class CalendarPageModel : PageModelBase
{
    #region Pror

    private ToDoContext Context { get; set; }
    public ObservableCollection<ToDoModel> Todos { get; set; }
    private ToDoModel _todo;
    public ToDoModel Todo
    {
        get => _todo;
        set
        {
            value = TodoLoad(value);
            SetField(ref _todo, value);
        }
    }

    #endregion

    #region Load

    private ToDoModel TodoLoad(ToDoModel todo)
    {
        Context.Entry(todo).Collection(x => x.Steps).Load();
        return todo;
    }

    #endregion

    #region DataOperation

    #region Add

    public void Add(ToDoModel todo)
    {
        Context.ToDos.Add(todo);
        Context.SaveChanges();
        Todos.Add(todo);
    }

    public void Add(StepModel? step)
    {
        if (step == null) return;
        var todo = Context.ToDos.FirstOrDefault(x => x.Key == _todo.Key);
        if (todo == null) return;
        todo.Steps.Add(step);
        Context.SaveChanges();
        Todo = todo;
    }

    #endregion

    #region Update

    public void Update(ToDoModel todo)
    {
        var model = Context.ToDos.FirstOrDefault(x => x.Key == todo.Key);
        if (model is null) return;
        model.Title = todo.Title;
        Context.SaveChanges();
    }

    public void Update(StepModel step)
    {
        var model = Context.Steps.FirstOrDefault(x => x.Key == step.Key);
        if (model is null) return;
        model.Context = step.Context;
        model.EndTime = step.EndTime;
        model.IsDone = step.IsDone;
        Context.SaveChanges();
    }

    #endregion

    #region Remove

    public void Remove(ToDoModel model)
    {
        Context.Remove(model);
        Context.SaveChanges();
    }

    public void Remove(StepModel model)
    {
        Context.Remove(model);
        Context.SaveChanges();
    }

    #endregion

    public ToDoModel? GetTodo(int key)
        => Context.ToDos.FirstOrDefault(x => x.Key == key);

    #endregion
    

    protected override void Init()
    {
        Context = new ToDoContext();
        Todos = new ObservableCollection<ToDoModel>(Context.ToDos);
    }
}